package com.example.casper.jnuexperiment2025.Data;

import android.content.Context;
import android.util.Log;

import com.example.casper.jnuexperiment2025.Hello03038Activity;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class DataBank {
    public static final String BOOK_DATA_FILE_NAME = "book.data";

    public void save(ArrayList<Book> books, Context context ) {
        try {
            FileOutputStream fileOut = context.openFileOutput(BOOK_DATA_FILE_NAME, Context.MODE_PRIVATE);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);

            out.writeObject(books);
            out.close();
            fileOut.close();
        } catch (Exception e) {
            Log.e("data save", e.toString());
        }
    }

    public ArrayList<Book> load(Context context) {
        ArrayList<Book> books = new ArrayList<>();
        try {
            FileInputStream fileIn = context.openFileInput(BOOK_DATA_FILE_NAME);
            ObjectInputStream in = new ObjectInputStream(fileIn);

            books = (ArrayList<Book>) in.readObject();
            in.close();
            fileIn.close();
        } catch (Exception e) {
            Log.e("data save", e.toString());
        }

        return books;
    }
}
